package com.kandinfo.base.admin.quartz;

import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import com.kandinfo.base.admin.service.ScheduleJobService;
import com.kandinfo.base.common.util.DateUtils;

/**
 * 
 * 初始化
 * 加载需要可执行的定时器
 * 
 * @author qiweiyang
 *
 */
@Service
public class InitJob implements ApplicationListener<ContextRefreshedEvent> {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(InitJob.class);
    
    @Autowired
    private ScheduleJobService scheduleJobService;
    
    private final static Object LOCK = new Object();
    private static boolean RUNNING_FLAG = false;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) {// root application context 没有parent，他就是老大.
        	synchronized (LOCK) {
    			if (RUNNING_FLAG) {
    				LOGGER.debug("InitJob has runned");
    				return;
    			}
    			LOGGER.debug("InitJob START");
    			RUNNING_FLAG = true;
    			Long start = System.currentTimeMillis();
    			
    			try {
					scheduleJobService.InitJob();
				} catch (SchedulerException e) {
					LOGGER.error("InitJob ERROR! ", e);
				}
    			
    			Long end = System.currentTimeMillis();
    			LOGGER.debug("InitJob END cost time："+DateUtils.getTimeDisplay(end.longValue()-start.longValue()));
    		}
        }
    }

}
